<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      class MyPromise {
        constructor(handle) {
          this["[[PromiseState]]"] = "pendding";
          this["[[PromiseResult]]"] = undefined;
          handle(this.#_resolve.bind(this), this.#_reject.bind(this));
          this.resolveFn = undefined;
          this.rejectFn = undefined;
        }
        // 私有方法 需要在前面加上#号，只能类的内部调用，外部不能调用
        #_resolve(val) {
          this["[[PromiseState]]"] = "fulfilled";
          this["[[PromiseResult]]"] = val;
          // 内部延迟执行
          setTimeout(() => {
            this.resolveFn(val); // 在调取 resolve的时候执行保存的onResolved函数
          });
        }

        #_reject(err) {
          this["[[PromiseState]]"] = "rejected";
          this["[[PromiseResult]]"] = err;
          setTimeout(() => {
            this.rejectFn(err);
          });
          setTimeout(() => {
            throw new Error(err); // 抛出错误
          });
        }

        then(onResolved, onRejected) {
          console.log("then方法执行了");
          // 赋值还没有执行
          this.resolveFn = onResolved;
          this.rejectFn = onRejected;
        }
      }

      let p = new MyPromise((resolve, reject) => {
        // setTimeout(() => {
        resolve("success");
        // }, 1000);
      });

      p.then(
        (res) => {
          console.log("执行了onResolved", res);
        },
        (err) => {
          console.log(err);
        }
      ); //调用类里的then方法
    </script>
  </body>
</html>
